<?php

namespace app\widgets;


use Yii;
use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Url;

class ShareWidget extends Widget {

    public $title;
    public $share_url;
    public $image;
    protected $shareButtons = [];
    public $shareClass = 'share';

    public function init() {
        parent::init();
        if (empty($this->share_url)) {
            $this->share_url = Url::to([Yii::$app->request->url], TRUE);
        }

        $this->shareButtons = [
            'qq' => [
                'icon' => 'qq', 'url' => Url::to("https://connect.qq.com/widget/shareqq/index.html?url={$this->share_url}&title={$this->title}&pics={$this->image}")
            ],
            'wechat' => [
                'icon' => 'wechat', 'url' => ''
            ],
            'weibo' => [
                'icon' => 'weibo', 'url' => Url::to("http://service.weibo.com/share/share.php?url={$this->share_url}&title={$this->title}&pic={$this->image}&searchPic=true")
            ],

            'twitter' => [
                'icon' => 'twitter', 'url' => Url::to("https://twitter.com/intent/tweet?text={$this->title}&pic={$this->image}&url={$this->share_url}")
            ],
            'facebook' => [
                'icon' => 'facebook', 'url' => Url::to("https://facebook.com/sharer/sharer.php?t={$this->title}&u={$this->share_url}&pic={$this->image}")
            ],
            'pinterest' => [
                'icon' => 'pinterest', 'url' => Url::to("https://pinterest.com/pin/create/button/?description={$this->title}&url={$this->share_url}&media={$this->image}")
            ],
        ];
    }

    public function run() {
        Yii::$app->view->registerJsFile('@theme/js/qrcode.min.js', ['depends' => 'yii\web\JqueryAsset']);
        $data = [];
        foreach ($this->shareButtons as $name => $button) {
            $icon = Html::tag('i', '', ['class' => "icon-{$button['icon']}"]);
            $id = strtolower($name);
            if ($id === 'wechat') {
                $qr_code[] = Html::tag('span', '', ['data-text' => $this->share_url, 'class' => 'qr_code']);
                $qr_code[] = Html::tag('span', '扫码分享到微信');
                $icon .= Html::tag('div', join("\n", $qr_code), ['class' => 'bd']);
//                $this->view->registerJs("$('.qrcode').qrcode({text: '{$this->share_url}'});");
                $button['url'] = 'javascript:void(0);';
            }
            $data[] = Html::a($icon, $button['url'], ['class' => "{$id}", 'target' => '_blank']);
        }
        return Html::tag('div', join("\n", $data), ['class' => "{$this->shareClass}"]);
    }
}